﻿using Admin.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;

namespace Admin.Controllers
{
    [Authorize(Roles = "Admin")]
    public class UsersAdminController : Controller
    {
        public const string Password = "Pass@word1";
        public UsersAdminController()
        {
        }

        public UsersAdminController(ApplicationUserManager userManager, ApplicationRoleManager roleManager)
        {
            UserManager = userManager;
            RoleManager = roleManager;
        }


        private ApplicationUserManager _userManager;
        public ApplicationUserManager UserManager
        {
            get
            {
                return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
            }
            private set
            {
                _userManager = value;
            }
        }

        private ApplicationRoleManager _roleManager;
        public ApplicationRoleManager RoleManager
        {
            get
            {
                return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
            }
            private set
            {
                _roleManager = value;
            }
        }

        private ApplicationDbContext _applicationDbContext;
        public ApplicationDbContext ApplicationDbContext
        {
            get
            {
                return _applicationDbContext ?? HttpContext.GetOwinContext().Get<ApplicationDbContext>();
            }
            private set
            {
                _applicationDbContext = value;
            }
        }

        #region 用户管理
        public ActionResult Users_Read([DataSourceRequest]DataSourceRequest request)
        {
            using (ApplicationDbContext)
            {
                var result = ApplicationDbContext.Users.Where(x => x.UserName != "admin").Select(x => new 
                {
                    Id = x.Id,
                    UserName = x.UserName,
                    Email = x.Email,
                    RoleList = x.Roles.Select(y => new SelectItem
                    {
                        Text = ApplicationDbContext.Roles.FirstOrDefault(z => z.Id == y.RoleId).Name,
                        Value = y.RoleId
                    })
                });

                return Json(result.ToDataSourceResult(request,x => new UserViewModel
                {
                    Id = x.Id,
                    UserName = x.UserName,
                    Email = x.Email,
                    RoleList = x.RoleList.ToList()
                }), JsonRequestBehavior.AllowGet);
            }
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult User_Create([DataSourceRequest] DataSourceRequest request, UserViewModel user)
        {
            if (user != null && ModelState.IsValid)
            {
                var dbUser = new ApplicationUser { UserName = user.UserName, Email = user.Email};
                var adminresult =  UserManager.Create(dbUser, Password);

                //Add User to the selected Roles 
                if (adminresult.Succeeded)
                {
                    if (user.RoleList != null)
                    {
                        var result =  UserManager.AddToRoles(dbUser.Id, user.RoleList.Select(x => x.Text).ToArray());
                        if (!result.Succeeded)
                        {
                            ModelState.AddModelError("", result.Errors.First());

                        }
                        else
                        {
                            user.Id = dbUser.Id;
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError("", adminresult.Errors.First());
                }

            }

            return Json(new[] { user }.ToDataSourceResult(request, ModelState));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult User_Update([DataSourceRequest] DataSourceRequest request, UserViewModel user)
        {
            if (user != null && ModelState.IsValid)
            {
                var dbUser =  UserManager.FindById(user.Id);
                if (dbUser != null)
                {

                    dbUser.UserName = user.UserName;
                    dbUser.Email = user.Email;

                    var userRoles = UserManager.GetRoles(user.Id);
                    var selectedRole = user.RoleList.Select(x => x.Text).ToArray();

                    selectedRole = selectedRole ?? new string[] {};

                    var result = UserManager.AddToRoles(user.Id, selectedRole.Except(userRoles).ToArray<string>());

                    if (!result.Succeeded)
                    {
                        ModelState.AddModelError("", result.Errors.First());
                    }
                    result = UserManager.RemoveFromRoles(user.Id, userRoles.Except(selectedRole).ToArray<string>());

                    if (!result.Succeeded)
                    {
                        ModelState.AddModelError("", result.Errors.First());
                    }
                }
            }

            return Json(new[] { user}.ToDataSourceResult(request, ModelState));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult User_Destroy([DataSourceRequest] DataSourceRequest request, UserViewModel user)
        {
            if (!string.IsNullOrEmpty(user?.Id))
            {
                var dbUser = UserManager.FindById(user.Id);
                if (dbUser != null)
                {
                    var result = UserManager.Delete(dbUser);
                    if (!result.Succeeded)
                    {
                        ModelState.AddModelError("", result.Errors.First());
                    }
                }
            }

            return Json(new[] { user }.ToDataSourceResult(request, ModelState));
        }
        #endregion


        //
        // GET: /Users/
        public async Task<ActionResult> Index()
        {
            ViewBag.ModuleName = "用户管理";
            ViewBag.ModuleLink = "#";
            ViewBag.PageName = "用户列表";
            ViewBag.PageTitle = "用户列表";
            return View(await UserManager.Users.Where(x => x.UserName!="admin").ToListAsync());
        }

        //
        // GET: /Users/Details/5
        public async Task<ActionResult> Details(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var user = await UserManager.FindByIdAsync(id);

            ViewBag.RoleNames = await UserManager.GetRolesAsync(user.Id);

            return View(user);
        }

        //
        // GET: /Users/Create
        public async Task<ActionResult> Create()
        {
            ViewBag.ModuleName = "用户管理";
            ViewBag.ModuleLink = "#";
            ViewBag.PageName = "新增用户";
            ViewBag.PageTitle = "新增用户";
            //Get the list of Roles
            ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync(), "Name", "Name");
            return View();
        }

        //
        // POST: /Users/Create
        [HttpPost]
        public async Task<ActionResult> Create(RegisterViewModel userViewModel, params string[] selectedRoles)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    UserName = userViewModel.UserName,
                    Email = userViewModel.Email
                };
                var adminresult = await UserManager.CreateAsync(user, userViewModel.Password);

                //Add User to the selected Roles 
                if (adminresult.Succeeded)
                {
                    if (selectedRoles != null)
                    {
                        var result = await UserManager.AddToRolesAsync(user.Id, selectedRoles);
                        if (!result.Succeeded)
                        {
                            ModelState.AddModelError("", result.Errors.First());
                            ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync(), "Name", "Name");
                            return View();
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError("", adminresult.Errors.First());
                    ViewBag.RoleId = new SelectList(RoleManager.Roles, "Name", "Name");
                    return View();

                }
                return RedirectToAction("Index");
            }
            ViewBag.RoleId = new SelectList(RoleManager.Roles, "Name", "Name");
            return View();
        }

        //
        // GET: /Users/Edit/1
        public async Task<ActionResult> Edit(string id)
        {
            ViewBag.ModuleName = "用户管理";
            ViewBag.ModuleLink = "#";
            ViewBag.PageName = "编辑用户";
            ViewBag.PageTitle = "编辑用户";
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var user = await UserManager.FindByIdAsync(id);
            if (user == null)
            {
                return HttpNotFound();
            }

            var userRoles = await UserManager.GetRolesAsync(user.Id);

            return View(new EditUserViewModel()
            {
                Id = user.Id,
                Email = user.Email,
                UserName = user.UserName,

                RolesList = RoleManager.Roles.ToList().Select(x => new SelectListItem()
                {
                    Selected = userRoles.Contains(x.Name),
                    Text = x.Name,
                    Value = x.Name
                })
            });
        }

        //
        // POST: /Users/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Edit(EditUserViewModel editUser, params string[] selectedRole)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByIdAsync(editUser.Id);
                if (user == null)
                {
                    return HttpNotFound();
                }

                user.UserName = editUser.UserName;
                user.Email = editUser.Email;


                var userRoles = await UserManager.GetRolesAsync(user.Id);
                editUser.RolesList = RoleManager.Roles.ToList().Select(x => new SelectListItem()
                {
                    Selected = userRoles.Contains(x.Name),
                    Text = x.Name,
                    Value = x.Name
                });

                selectedRole = selectedRole ?? new string[] { };

                var result = await UserManager.AddToRolesAsync(user.Id, selectedRole.Except(userRoles).ToArray<string>());

                if (!result.Succeeded)
                {
                    ModelState.AddModelError("", result.Errors.First());
                    return View(editUser);
                }
                result = await UserManager.RemoveFromRolesAsync(user.Id, userRoles.Except(selectedRole).ToArray<string>());

                if (!result.Succeeded)
                {
                    ModelState.AddModelError("", result.Errors.First());
                    return View(editUser);
                }
                return RedirectToAction("Index");
            }
            ModelState.AddModelError("", "编辑用户错误.");
            return View(editUser);
        }

        //
        // GET: /Users/Delete/5
        public async Task<ActionResult> Delete(string id)
        {
            ViewBag.ModuleName = "用户管理";
            ViewBag.ModuleLink = "#";
            ViewBag.PageName = "删除用户";
            ViewBag.PageTitle = "删除用户";
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var user = await UserManager.FindByIdAsync(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }

        //
        // POST: /Users/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> DeleteConfirmed(string id)
        {
            if (ModelState.IsValid)
            {
                if (id == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }

                var user = await UserManager.FindByIdAsync(id);
                if (user == null)
                {
                    return HttpNotFound();
                }
                var result = await UserManager.DeleteAsync(user);
                if (!result.Succeeded)
                {
                    ModelState.AddModelError("", result.Errors.First());
                    return View();
                }
                return RedirectToAction("Index");
            }
            return View();
        }

        //
        // GET: /Users/
        public  ActionResult IndexGrid()
        {
            ViewBag.ModuleName = "用户管理";
            ViewBag.ModuleLink = "#";
            ViewBag.PageName = "用户管理";
            ViewBag.PageTitle = "用户管理";

            var roles = RoleManager.Roles.Select(x => new SelectItem()
            {
                Text = x.Name,
                Value = x.Id
            }).ToList();
            
            ViewData["MultiLevel"] = roles;
            var defaultRole = new List<SelectItem> {roles.First()};
            ViewData["defaultRole"] = defaultRole;
            return View();
        } 
    }
}
